package com.example.demo.sentinel;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SentinelRuleInitializer {

    //@PostConstruct
    private static void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<FlowRule>();
        FlowRule rule1 = new FlowRule();
        //定义资源名称
        rule1.setResource("flowControl");
        //限流阈值
        rule1.setCount(1);
        //限流阈值类型 0-并发数 1-QPS
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //超出阈值后处理手段 0-直接拒绝 1-冷启动 2-匀速器 3-
        rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        //应用来源限制
        rule1.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
    }

    @PostConstruct
    private static void initDegradeRule() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule("flowControl")
                //熔断策略，支持 0-慢调用比例/ 1-异常比例/ 2-异常数策略
                .setGrade(CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType())
                //慢调用比例模式下为慢调用临界 响应时间（超出该值计为慢调用）；异常比例/异常数模式下为对应的阈值
                .setCount(5)
                // 熔断时长，单位为 s
                .setTimeWindow(10)
                //慢调用比例阈值，仅慢调用比例模式有效（1.8.0 引入）
                .setSlowRatioThreshold(0.6)
                // 熔断触发的最小请求数，请求数小于该值时即使异常比率超出阈值也不会熔断（1.7.0 引入）
                .setMinRequestAmount(1)
                //统计时长（单位为 ms），如 60*1000 代表分钟级（1.8.0 引入）
                .setStatIntervalMs(20000);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
}
